const express = require('express');
const router = express.Router();
const { Category, Course } = require('../../models');
const { Op } = require('sequelize');
const { NotFoundError } = require('../../utils/errors');
const { success, failure } = require('../../utils/responses');

/**
 * 公共方法：查询当前分类
 */
async function getCategory(req) {
  // 获取分类 ID
  const { id } = req.params;

  // 查询当前分类
  const category = await Category.findByPk(id);

  // 如果没有找到，就抛出异常
  if (!category) {
    throw new NotFoundError(`ID: ${id}的分类未找到。`)
  }

  return category;
}
/**
 * 公共方法：白名单过滤
 * @param req
 * @returns {{name, rank: (string|string|DocumentFragment|*)}}
 */
function filterBody(req) {
  return {
    name: req.body.name,
    rank: req.body.rank
  };
}
/**
 * 查询分类列表
 * GET /admin/categories
 */
router.get('/', async function (req, res) {
  try {
    // 定义查询条件

    const { name } = req.query;

    if (name) {
      // 模糊搜索
      condition.where.name = {
        [Op.like]: `%${name}%`
      };
    }
    const condition = {
      order: [['id', 'DESC']],
    };
    // 查询数据
    const categories = await Category.findAll(condition);
    success(res, '查询分类列表成功。', {
      categories: categories,
    });

  } catch (error) {
    // 返回错误信息
    failure(res, error);
  }
});
/**
 * 查询分类详情
 */
router.get('/:id', async function (req, res) {
  try {
    const category = await getCategory(req);
    success(res, '查询分类成功。', { category });

  } catch (error) {
    failure(res, error);
  }
})
/**
 * 创建分类
 */
router.post("/", async function (req, res) {
  try {
    const body = filterBody(req);
    const category = await Category.create(body);
    success(res, '创建分类成功。', { category }, 201);
  } catch (error) {
    failure(res, error);

  }
})
/**
 * 删除分类
 */
router.delete('/:id', async function (req, res) {
  try {
    const category = await getCategory(req);
    // 为了防止孤儿记录,先查一下有没有课程了，有课程分类不能删除
    const count = await Course.count({
      where: {
        categoryId: req.params.id
      }
    });
    if (count > 0) {
      throw new Error('当前分类有课程，无法删除。');
    }
    await category.destroy()
    success(res, '删除分类成功。');

  } catch (error) {
    failure(res, error);
  }
})
/**
 * 更新分类
 */
router.put('/:id', async function (req, res) {
  try {
    const category = await getCategory(req);
    const body = filterBody(req);
    await category.update(body)
    success(res, '更新分类成功。', { category });

  } catch (error) {
    failure(res, error);
  }
})
module.exports = router;
